<?php

namespace Wechat\Controller;

use Think\Controller;

class ApiController extends Controller {

    /**

     * 微信消息接口入口

     * 所有发送到微信的消息都会推送到该操作

     * 所以，微信公众平台后台填写的api地址则为该操作的访问地址

     */
    public function index($id = '') {

        import("@.Util.Wechat");

        $token = I('get.Token') ? I('get.Token') : C('token'); //微信后台填写的TOKEN

        /* 加载微信SDK */

        $wechat = new \Wechat($token);


        /* 获取请求信息 */

        $data = $wechat->request();

        $data['openid'] = $data['FromUserName'];

        if ($data && is_array($data)) {

            S('weixin', $wechat);

            S('data', $data);
        
            /**

             * 你可以在这里分析数据，决定要返回给用户什么样的信息

             * 接受到的信息类型有9种，分别使用下面九个常量标识

             * Wechat::MSG_TYPE_TEXT       //文本消息

             * Wechat::MSG_TYPE_IMAGE      //图片消息

             * Wechat::MSG_TYPE_VOICE      //音频消息

             * Wechat::MSG_TYPE_VIDEO      //视频消息

             * Wechat::MSG_TYPE_MUSIC      //音乐消息

             * Wechat::MSG_TYPE_NEWS       //图文消息（推送过来的应该不存在这种类型，但是可以给用户回复该类型消息）

             * Wechat::MSG_TYPE_LOCATION   //位置消息

             * Wechat::MSG_TYPE_LINK       //连接消息

             * Wechat::MSG_TYPE_EVENT      //事件消息

             *

             * 事件消息又分为下面五种

             * Wechat::MSG_EVENT_SUBSCRIBE          //订阅

             * Wechat::MSG_EVENT_SCAN               //二维码扫描

             * Wechat::MSG_EVENT_LOCATION           //报告位置

             * Wechat::MSG_EVENT_CLICK              //菜单点击

             * Wechat::MSG_EVENT_MASSSENDJOBFINISH  //群发消息成功

             */
            //根据来源信息的类型使用不同的方法路径进行处理

            Switch ($data['MsgType']) {

                case \Wechat::MSG_TYPE_TEXT: //文本

                    $arr = $this->text($data);

                    break;



                case \Wechat::MSG_TYPE_IMAGE: //图片

                    $arr = image($data);

                    break;



                case \Wechat::MSG_TYPE_EVENT: //事件

                    $arr = $this->event($data);
                    
                    break;



                default:

                    $content = "该功能暂未开放"; //回复内容，回复不同类型消息，内容的格式有所不同

                    $type = 'text'; //回复消息的类型
            }

            /////////////////////////////////////////////////////////////////////

            $content = $arr['content'] ? $arr['content'] : $content;

            $type = $arr['type'] ? $arr['type'] : $type;

            /* 响应当前请求(自动回复) */

            S('content', $content);

            if(empty($arr) || !isset($arr) || $arr == null) {
                exit("");
            } 

            $wechat->response($content, $type);
            /**

             * 响应当前请求还有以下方法可以只使用

             * 具体参数格式说明请参考文档

             * 

             * $wechat->replyText($text); //回复文本消息

             * $wechat->replyImage($media_id); //回复图片消息

             * $wechat->replyVoice($media_id); //回复音频消息

             * $wechat->replyVideo($media_id, $title, $discription); //回复视频消息

             * $wechat->replyMusic($title, $discription, $musicurl, $hqmusicurl, $thumb_media_id); //回复音乐消息

             * $wechat->replyNews($news, $news1, $news2, $news3); //回复多条图文消息

             * $wechat->replyNewsOnce($title, $discription, $url, $picurl); //回复单条图文消息

             * 

             */
        }
    }

    /////////////////////////////////
    //分支功能

    protected function text($data) {

        switch ($data['Content']) {



            default:

                $arr = null;

                break;
        }

        return $arr;
    }

    protected function event($data) {

        switch ($data['Event']) {

            case \Wechat::MSG_EVENT_SUBSCRIBE:  //关注

                if(!isNullOrEmpty($data["openid"])) {

                    $customer = D("Customer")->queryByMap(array("openid"=>$data["openid"]));

                    if(isNullOrEmpty($customer)) {

                        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".access_token()."&openid=".$data["openid"]."&lang=zh_CN";
                        $info = json_decode(curl($url),true);

                        $nicknameTmp = json_encode($info["nickname"]);
                        $nicknameTmp = preg_replace("#(\\\ud[0-9a-f]{3})#ie","",$nicknameTmp);
                        $nicknameNoEmoji = json_decode($nicknameTmp);

                        $customerData["nickname"] = $nicknameNoEmoji;
                        $customerData["openid"] = $data["openid"];
                        $customerData["headimgurl"] = $info["headimgurl"];
                        $customerData["create_time"] = getCurrentDate();
                        $customerData["subscribe"] = 1;
                        if(!isNullOrEmpty($customerData)) {
                            D("Customer")->add($customerData);
                        }

                    } else {
                        $customer["subscribe"] = 1;
                        D("Customer")->updateInfo($customer);
                    }

                    cookie("openid", $data["openid"]);

                    $browseTarget = unserialize(S("sub_".$data["openid"]));

                    if(!isNullOrEmpty($browseTarget)) {
                        $browseType = $browseTarget['browse_type'];
                        $targetId = $browseTarget['target_id'];

                        echo $this->sendPicTextData($data,$browseType,$targetId);

                        S("sub_".$data["openid"],NULL);
                    }

                    $arr = null;

                    exit();
                }

                break;

            case unsubscribe:  //取消关注

                $customer = D("Customer")->queryByMap(array("openid"=>$data["openid"]));

                $customer["subscribe"] = 0;
                D("Customer")->updateInfo($customer);

                cookie("openid", null);

                break;

            default:

                //$arr['content'] = $data['Event']."事件暂未开放"; //回复内容，回复不同类型消息，内容的格式有所不同
                //$arr['type']    = 'text'; //回复消息的类型

                $arr = null;

                break;
        }

        return $arr;
    }

    protected function click($data) {

        switch ($data['EventKey']) {

            default:

                $arr['content'] = "该功能暂未开放"; //回复内容，回复不同类型消息，内容的格式有所不同

                $arr['type'] = 'text'; //回复消息的类型

                break;
        }



        return $arr;
    }

    protected function image($data) {

        $arr['content'] = "你是说：" . $data['Content']; //回复内容，回复不同类型消息，内容的格式有所不同

        $arr['type'] = 'text'; //回复消息的类型

        return $arr;
    }

    /////////////////////////////
    //自定义菜单功能



    function menulist() {

        echo $url = 'https://api.weixin.qq.com/cgi-bin/menu/get?access_token=' . access_token();

        //$post = array(124,535,635,42);

        $arr = json_decode(curl($url), true);

        dump($arr);

        echo "<br/>";

        dump(json_encode($arr));
    }

    function menuadd() {

        if (I('get.key') != 'luoe123') {

            exit("参数错误");
        }

        $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" . access_token();

        $data = resetMenu();

        $aaa = curl($url, $data);

    }

    //////////////////////////////////
    /// view获取openid



    function auth() {

        //dump(I('get.'));

        $state = I('get.state');

        $pstr = I('get.pstr');
        $code = I('get.code');

        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . C('appid') . "&secret=" . C('appsecret') . "&code=" . $code . "&grant_type=authorization_code";

        $r = json_decode(curl($url), true);

        //dump($r);

        $openid = $r['openid'];

        $db = M('user');

        $sql = $db->where("openid = '$openid'")->find();

        cookie('uid', $sql['uid'], 0);
        
        cookie('openid', $sql['openid'], 0);
 
    }

    function auth2() {

        $code = '04143f67c046f5e587ae729d6cbef9fH';

        echo $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . C('appid') . "&secret=" . C('appsecret') . "&code=" . $code . "&grant_type=authorization_code";

        $r = json_decode(curl($url), true);

        dump($r);
    }

    function auth3() {

        $state = I('get.state');

        $code = I('get.code');
                
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . C('appid') . "&secret=" . C('appsecret') . "&code=" . $code . "&grant_type=authorization_code";

        $r = json_decode(curl($url), true);

        $openid = $r['openid'];

        if(!isNullOrEmpty($r["openid"])) {
            $customer = D("Customer")->queryByMap(array("openid"=>$openid));

            if(isNullOrEmpty($customer)) {
                $url = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $r['access_token'] . "&openid=" . $openid . "&lang=zh_CN";
                $r = json_decode(curl($url), true);

                $nicknameTmp = json_encode($r["nickname"]);
                $nicknameTmp = preg_replace("#(\\\ud[0-9a-f]{3})#ie","",$nicknameTmp);
                $nicknameNoEmoji = json_decode($nicknameTmp);

                $customerData["nickname"] = $nicknameNoEmoji;
                $customerData["openid"] = $r["openid"];
                $customerData["headimgurl"] = $r["headimgurl"];
                $customerData["create_time"] = getCurrentDate();
                if(!isNullOrEmpty($customerData)) {
                    D("Customer")->add($customerData);
                }
            }
            cookie("openid", $r["openid"]);
        }
        
        header("Location: " . urldecode($state));
    }

    ///////////////////////////
    //客服消息

    function send($openid, $text) {

        //$uid = I('get.openid');
        //$text = I('post.text');
        //$uid = 'ozj3Us5MtH-WdZJ8cvZWfYMuj4CQ';

        $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" . access_token();

        $post = array(
            "touser" => $openid,
            "msgtype" => "text",
            "text" => array(
                "content" => $text,
            ),
        );

        $data = json_encode2($post);

        $aaa = curl($url, $data);

        return $aaa;
    }

    /////////////////////////
    //用户功能

    function userlist() {

        $url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" . access_token();
        if (I('get.openid')) {
            $url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" . access_token() . "&next_openid=" . I('get.openid');
        }
        $arr = curl($url);

        $arr2 = json_decode($arr, true);

        S('Wechat_user_list', $arr2[data][openid]);

        dump($arr2[data][openid]);
    }

    function userxiufu() {

        G('begin');
        //$this -> userlist();

        $user_list = S('Wechat_user_list');

        $user = D('User');



        $yes = 0;

        $no = 0;

        foreach ($user_list as $val) {

            $data['openid'] = $val;



            /* if(!$user->create($data)){

              echo $user->getError()."||".$data['openid']."<br />";

              }else{

              echo "可以写入".$data['openid']."<br />";

              $user -> add($data);

              }

             */

            //$user -> create($data);

            if ($user->where($data)->find()) {

                echo "<br />重复了" . $val;

                $yes++;
            } else {

                echo "<br />准备写入" . $val;

                $uid = $user->add($data);

                $update = A('User');

                $update->updata($uid);

                $no++;
            }

            //$user -> add($data);
        }

        echo "<br/>当前写入" . $no . "已存在" . $yes;

        G('end');

        echo "<br/>执行时间：" . G('begin', 'end') . 's';
    }

    /////////////////////////////////////////
    //短信

    protected function sms($tel, $content) {

        $ch = curl_init();



        curl_setopt($ch, CURLOPT_URL, "http://sms-api.luosimao.com/v1/status.json");

        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);

        curl_setopt($ch, CURLOPT_HEADER, FALSE);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);



        curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);

        curl_setopt($ch, CURLOPT_USERPWD, 'api:key-' . C('mmskey'));



        $res = curl_exec($ch);

        curl_close($ch);

        //$res  = curl_error( $ch );

        dump($res);
    }

    //////////////////////////////////
    //调试

    function debug() {

        dump(S('weixin'));

        dump(S('data'));

        dump(S('SUBSCRIBE'));

        dump(S('sql'));

        dump(S('code'));

        //dump(S('Wechat_user_list'));
    }

    protected function sendPicTextData($data,$browseType,$targetId) {

        $newsTpl = "<xml>
						<ToUserName><![CDATA[%s]]></ToUserName>
						<FromUserName><![CDATA[%s]]></FromUserName>
						<CreateTime>%s</CreateTime>
						<MsgType><![CDATA[%s]]></MsgType>
						<ArticleCount>%s</ArticleCount>
						<Articles>
							<item>
								<Title><![CDATA[%s]]></Title>
								<Description><![CDATA[%s]]></Description>
								<PicUrl><![CDATA[%s]]></PicUrl>
								<Url><![CDATA[%s]]></Url>
							</item>
						</Articles>
					</xml>";

        if($browseType == C('BROWSE_TYPE.PRODUCT')) {

            $product = D('Product')->where(array('product_id' => $targetId))->find();

            $resultStr = sprintf(
                $newsTpl,
                $data['FromUserName'],
                $data['ToUserName'],
                time(),
                'news',
                1,
                "欢迎购买 - ".$product['product_name'],
                $product['brief'],
                $product['image'],
                'http://'.$_SERVER['HTTP_HOST'].'/wechat/product/index/id/'.$targetId
            );

        } elseif ($browseType == C('BROWSE_TYPE.SHARE')) {

            $group = D('Group')->alias('g')
                ->join('LEFT JOIN __ROUND__ r ON g.round_id = r.round_id')
                ->join('LEFT JOIN __PRODUCT__ p ON r.product_id = p.product_id')
                ->field('p.*, g.member_number, g.buy_number')
                ->where(array('g.group_id' => $targetId))
                ->find();

            $resultStr = sprintf(
                $newsTpl,
                $data['FromUserName'],
                $data['ToUserName'],
                time(),
                'news',
                1,
                "欢迎入团 - ".$group['product_name'],
                "团内已有".$group['member_number']."人，共购买".$group['buy_number']."份",
                $group['image'],
                'http://'.$_SERVER['HTTP_HOST'].'/wechat/product/share/id/'.$targetId
            );

        } elseif ($browseType == C('BROWSE_TYPE.JOIN')) {

            $product = D('Product')->where(array('product_id' => $targetId))->find();

            $resultStr = sprintf(
                $newsTpl,
                $data['FromUserName'],
                $data['ToUserName'],
                time(),
                'news',
                1,
                "欢迎继续购买 - ".$product['product_name'],
                $product['brief'],
                $product['image'],
                'http://'.$_SERVER['HTTP_HOST'].'/wechat/product/join/id/'.$targetId
            );

        }

        return $resultStr;
    }

//    protected function sendPicTextData($data) {
//        $ArticleCount = 1;
//        $newsTpl = "<xml>
//						<ToUserName><![CDATA[%s]]></ToUserName>
//						<FromUserName><![CDATA[%s]]></FromUserName>
//						<CreateTime>%s</CreateTime>
//						<MsgType><![CDATA[%s]]></MsgType>
//						<ArticleCount>%s</ArticleCount>
//						<Articles>
//							<item>
//								<Title><![CDATA[%s]]></Title>
//								<Description><![CDATA[%s]]></Description>
//								<PicUrl><![CDATA[%s]]></PicUrl>
//								<Url><![CDATA[%s]]></Url>
//							</item>
//						</Articles>
//					</xml>";
//
//        $resultStr = sprintf($newsTpl, $data['FromUserName'], $data['ToUserName'], time(), 'news', $ArticleCount, '测试图文标题', '测试图文内容', 'https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png', 'http://www.baidu.com');
//        return $resultStr;
//    }

    public function debugWechatPay() {

        echo C('rooturl') . U('/Wechat/Api/WechatPay?orderId=1');

    }

    public function WechatPay() {
    
    	$order=$GLOBALS["HTTP_RAW_POST_DATA"];

    	$array_data = json_decode(json_encode(simplexml_load_string($order, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
  
    	if($array_data['return_code']=='SUCCESS') {

    		echo 'SUCCESS';

            //查找支付记录
            $payMap['out_trade_no'] = $array_data['out_trade_no'];
            $pay = D('Pay')->where($payMap)->find();

            if(!$pay['status']) {

                //修改支付记录
                $payData['status'] = 1;
                $payData['update_time'] = getCurrentDate();
                $payData['pay_trade_no'] = $array_data['transaction_id'];

                D('pay')->where($payMap)->save($payData);

                //查找订单
                $orderMap['pay_id'] = $pay['pay_id'];
                $order = D("order")->where($orderMap)->find();

                //修改订单状态
                $orderData["status"] = C("ORDER_STATUS.WAITING_OPEN");

                D('Order')->where(array("order_id"=>$order["order_id"]))->save($orderData);

                //查找群组
                $group = D('Group')->where(array('group_id' => $order['group_id']))->find();

                //查找轮次
                $round = D('Round')->where(array('round_id' => $order['round_id']))->find();

                //查找产品
                $product = D('Product')->where(array('product_id' => $round['product_id']))->find();

                if($round["status"] == C("ROUND_STATUS.WAITING")) {

                    //查找群成员
                    $groupMemberMap['group_id'] = $order['group_id'];
                    $groupMemberMap['customer_id'] = $order['customer_id'];
                    $groupMember = D('GroupMember')->where($groupMemberMap)->find();

                    //判断支付用户是否为团长
                    if($group['customer_id'] == $order['customer_id']) {

                        if($group['status'] == C('GROUP_STATUS.WAITING_PAY')) {

                            //修改团状态
                            $groupStatusData['status'] = C('GROUP_STATUS.WAITING_JOIN');

                            //保存群信息
                            D('Group')->where(array('group_id' => $order['group_id']))->save($groupStatusData);

                            //计算群数量
                            $groupCountMap['round_id'] = $order['round_id'];
                            $groupCountMap['status'] = C('GROUP_STATUS.WAITING_JOIN');

                            $groupCount = D('Group')->where($groupCountMap)->count();

                            //增加轮次中的团数量
                            $roundGroupNumberData['group_number'] = $groupCount;

                            //保存轮次信息
                            D('Round')->where(array('round_id' => $order['round_id']))->save($roundGroupNumberData);

                        } else if($group['status'] == C('GROUP_STATUS.WAITING_JOIN')) {

                            //计算群购买数量
                            $orderGroupSumMap['group_id'] = $order['group_id'];
                            $orderGroupSumMap['status'] = C("ORDER_STATUS.WAITING_OPEN");

                            $groupBuyNumber = D('Order')->where($orderGroupSumMap)->sum('number');

                            //修改群信息
                            $groupBuyNumberData['buy_number'] = $groupBuyNumber;

                            //保存群信息
                            D('Group')->where(array('group_id' => $order['group_id']))->save($groupBuyNumberData);

                            //计算购买数量
                            $orderMemberSumMap['group_id'] = $order['group_id'];
                            $orderMemberSumMap['customer_id'] = $order['customer_id'];
                            $orderMemberSumMap['status'] = C("ORDER_STATUS.WAITING_OPEN");

                            $memberBuyNumber = D('Order')->where($orderMemberSumMap)->sum('number');

                            //修改群成员信息
                            $groupMemberData['number'] = $memberBuyNumber;
                            $groupMemberData['update_time'] = getCurrentDate();

                            D('GroupMember')->where(array('member_id' => $groupMember['member_id']))->save($groupMemberData);

                        }

                    } else {

                        if(!isNullOrEmpty($groupMember)) {

                            //计算购买数量
                            $orderMemberSumMap['group_id'] = $order['group_id'];
                            $orderMemberSumMap['customer_id'] = $order['customer_id'];
                            $orderMemberSumMap['status'] = C("ORDER_STATUS.WAITING_OPEN");

                            $memberBuyNumber = D('Order')->where($orderMemberSumMap)->sum('number');

                            //修改群成员信息
                            $groupMemberData['number'] = $memberBuyNumber;
                            $groupMemberData['update_time'] = getCurrentDate();

                            D('GroupMember')->where(array('member_id' => $groupMember['member_id']))->save($groupMemberData);

                        } else {

                            //添加群成员信息
                            $groupMemberData["group_id"] = $group['group_id'];
                            $groupMemberData["customer_id"] = $order['customer_id'];
                            $groupMemberData["create_time"] = getCurrentDate();
                            $groupMemberData["number"] = $order['number'];
                            $groupMemberData["update_time"] = getCurrentDate();
                            $groupMemberData["reward"] = 0;

                            D("GroupMember")->add($groupMemberData);

                            //计算群成员数量
                            $groupMemberCountMap['group_id'] = $order['group_id'];

                            $groupMemberCount = D('GroupMember')->where($groupMemberCountMap)->count();

                            //增加群成员数量
                            $groupMemberNumberData['member_number'] = $groupMemberCount;

                            //保存群信息
                            D('Group')->where(array('group_id' => $order['group_id']))->save($groupMemberNumberData);

                        }

                        //计算群购买数量
                        $orderGroupSumMap['group_id'] = $order['group_id'];
                        $orderGroupSumMap['status'] = C("ORDER_STATUS.WAITING_OPEN");

                        $groupBuyNumber = D('Order')->where($orderGroupSumMap)->sum('number');

                        //增加群购买数量
                        $groupBuyNumberDataData['buy_number'] = $groupBuyNumber;

                        //保存群信息
                        D('Group')->where(array('group_id' => $order['group_id']))->save($groupBuyNumberDataData);

                    }

                    //计算本轮购买数量
                    $orderRoundSumMap['round_id'] = $order['round_id'];
                    $orderRoundSumMap['status'] = C("ORDER_STATUS.WAITING_OPEN");
                    $roundJoinNumber = D('Order')->where($orderRoundSumMap)->sum('number');

                    //增加轮次购买数量及进度
                    $roundData['join_number'] = $roundJoinNumber;
                    $roundData['progress'] = round($roundJoinNumber/$product['price'],2)*100;

                    //保存轮次信息
                    D('Round')->where(array('round_id' => $order['round_id']))->save($roundData);

                    //todo 异步下单
                    curlPost('http://114.215.113.76:9502/genOrderRecord',array('orderId' => $order['order_id']));

                    //查找群组
                    $group = D('Group')->where(array('group_id' => $order['group_id']))->find();

                    //查找用户
                    $customer = D('Customer')->where(array('customer_id' => $order['customer_id']))->find();

                    //推送支付成功模板消息
                    $messageData['openid'] = $customer['openid'];
                    $messageData['url'] = 'http://'.$_SERVER['HTTP_HOST'].U('Order/recordListPage',array('id' => $order['order_id']));
                    $messageData['product_name'] = $product['product_name'];
                    $messageData['order_no'] = $pay['out_trade_no'];
                    $messageData['member_number'] = $group['member_number'];

                    orderSuccess($messageData);

                    //todo 异步推送通知
                    $pushData['orderId'] = $order['order_id'];
                    curlPost('http://114.215.113.76:9502/pushNotification',$pushData);

                }

            }

        }

    }

    public function WechatPayGift() {

        $order=$GLOBALS["HTTP_RAW_POST_DATA"];

        $array_data = json_decode(json_encode(simplexml_load_string($order, 'SimpleXMLElement', LIBXML_NOCDATA)), true);

        if($array_data['return_code']=='SUCCESS') {

            echo 'SUCCESS';

            //查找支付记录
            $payMap['out_trade_no'] = $array_data['out_trade_no'];
            $pay = D('Pay')->where($payMap)->find();

            if(!$pay['status']) {
                //修改支付记录
                $payData['status'] = 1;
                $payData['update_time'] = getCurrentDate();
                $payData['pay_trade_no'] = $array_data['transaction_id'];

                D('pay')->where($payMap)->save($payData);

                //查找订单
                $giftOrderMap['pay_id'] = $pay['pay_id'];
                $giftOrder = D("GiftOrder")->where($giftOrderMap)->find();

                //修改奖品记录状态
                $giftOrderData['status'] = C('DEFAULT_YN.YES');
                D('GiftOrder')->where(array('gift_order_id' => $giftOrder['gift_order_id']))->save($giftOrderData);

                $order = D('Order')->alias('o')
                    ->join('LEFT JOIN __ROUND__ r ON o.round_id = r.round_id')
                    ->join('LEFT JOIN __PRODUCT__ p ON r.product_id = p.product_id')
                    ->join('LEFT JOIN __CUSTOMER__ c ON o.customer_id = c.customer_id')
                    ->field('o.*, c.openid, p.product_name')
                    ->where(array('o.order_id' => $giftOrder['order_id']))
                    ->find();

                //改变余额
                $sql = "UPDATE __CUSTOMER__ c
                    LEFT JOIN __GROUP_MEMBER__ gm ON c.customer_id = gm.customer_id
                    SET c.available_assets = ROUND(c.available_assets + gm.reward,2),
                    c.total_assets = ROUND(c.total_assets + gm.reward,2)
                    WHERE gm.group_id = " .$order['group_id']. "
                    AND gm.customer_id != ".$order['customer_id'];

                M()->execute($sql);

                //增加流水
                $groupMemberMap['group_id'] = $order['group_id'];
                $groupMemberMap['customer_id'] = array('neq',$order['customer_id']);
                $groupMemberList = D('GroupMember')->where($groupMemberMap)->select();

                foreach ($groupMemberList as $groupMember) {
                    $accountDetailData[] = array('money' => $groupMember['reward'], 'customer_id' => $groupMember['customer_id'],
                        'create_time' => getCurrentDate(), 'type' => C('ACCOUNT_DETAIL_TYPE.WIN'), 'refer_id' => $groupMember['group_id']);
                }

                D('AccountDetail')->addAll($accountDetailData);

                //修改订单状态
                $orderMap['group_id'] = $order['group_id'];
                $orderMap['status'] = C('ORDER_STATUS.WAITING_CHOOSE');

                $orderData['status'] = C('ORDER_STATUS.WIN');

                D('Order')->where($orderMap)->save($orderData);

                //修改轮次状态
                $roundData['pie_type'] = C('PIE_TYPE.GIFT');
                D('Round')->where(array('round_id' => $order['round_id']))->save($roundData);

                //推送下单成功模板消息
                $messageData['openid'] = $order['openid'];
                $messageData['url'] = 'http://'.$_SERVER['HTTP_HOST'].U('Product/winDetail',array('id' => $order['group_id']));
                $messageData['product_name'] = $order['product_name'];

                repeatOrderSuccess($messageData);

                //todo 异步推送中奖团
                curlPost('http://114.215.113.76:9502/pushWechat',array('groupId' => $order['group_id']));

            }

        }

    }

    public function WechatPayVip() {

        $order=$GLOBALS["HTTP_RAW_POST_DATA"];

        $array_data = json_decode(json_encode(simplexml_load_string($order, 'SimpleXMLElement', LIBXML_NOCDATA)), true);

        if($array_data['return_code']=='SUCCESS')
        {
            echo 'SUCCESS';

            //查找支付记录
            $payMap['out_trade_no'] = $array_data['out_trade_no'];
            $pay = D('pay')->where($payMap)->find();

            //修改支付记录
            $payData['status'] = 2;
            $payData['update_time'] = getCurrentDate();
            $payData['pay_trade_no'] = $array_data['transaction_id'];

            D('pay')->where($payMap)->save($payData);

            //VIP支付状态修改
            $vipRecordMap['pay_id'] = $pay['pay_id'];

            $vipRecordData['pay_status'] = 2;

            D('vipRecord')->where($vipRecordMap)->save($vipRecordData);

            //修改用户VIP状态
            $vipRecord = D('vipRecord')->where($vipRecordMap)->find();

            $userData['status'] = 3;
            $userData['vip_end_time'] = $vipRecord['end_time'];

            D('user')->where(array("user_id" => $vipRecord['user_id']))->save($userData);

            //发送消息
            $user = D('user')->where(array('user_id'=>$vipRecord['user_id']))->find();

            WeSend($user['openid'], '恭喜！您已成为尊贵的相遇未名VIP会员');

        }
    }

    /**
     * 订单支付成功
     * @param type $money
     * @param type $param
     */
    public function pay($money, $param) {
    	
        $orderId = $param['orderId'];
        
        $order = M('order')->where('order_id='.$orderId)->find();
        
        $pay = M('pay')->where('pay_id='.$order['pay_id'])->find();
        
    	$payMap['pay_id'] = $pay['pay_id'];       
        $payData['status'] = 1;
        $payData['update_time'] = time();
        $payData['pay_source'] = 0;
        $payData['callback'] = 'http://wx.congyicn.com/Wechat/Api/Pay/orderId='.$orderId;
        
        M('pay')->where($payMap)->save($payData);

        $orderMap['order_id'] = $orderId;

        $orderData['status'] = 1;
        $orderData['pay_time'] = time();

        M('order')->where($orderMap)->save($orderData);

    }
}
